var log = function()
{
    if (typeof console == "object" && console.log)
    {
        console.log.apply(console, arguments);
    }
}
    
var Xmpp = 
{
    connection:null,
    
    connect : function()
    {
       var username = $("#username").val();
       var password = $("#password").val();

       log("Connecting ", username, "with password ", password);


       var connection = new Strophe.Connection("http://bosh.metajack.im:5280/xmpp-httpbind");
       connection.connect(username, password, Xmpp.connection_status);      
       Xmpp.connection = connection;
    },
    
    disconnect : function()
    {
       Xmpp.connection.disconnect();
       Xmpp.connection = null;
    },
    
    connection_status : function(status)
    {
        var connected = false;
        
        if (status == Strophe.Status.CONNECTING)
        {
           jQuery('#connection_create').showLoading();            
           log("CONNECTING to jabber server");
        }
        else if (status == Strophe.Status.AUTHENTICATING)
        {
           jQuery('#connection_create').showLoading();            
           log("AUTHENTICATING from jabber server");
        }        
        if (status == Strophe.Status.CONNECTED)
        {
           connected = true; 
           jQuery('#connection_create').hideLoading(); 
           log("CONNECTED to jabber server");
        }      
        else if (status == Strophe.Status.DISCONNECTING)
        {
           jQuery('#connection_create').showLoading();            
           log("DISCONNECTING from jabber server");
        }        
        else if (status == Strophe.Status.DISCONNECTED)
        {
           jQuery('#connection_create').hideLoading();  
           log("DISCONNECTED from jabber server");
        }
        else if (status == Strophe.Status.CONNFAIL)
        {
           jQuery('#connection_create').hideLoading();  
           log("CONNFAIL from jabber server");
        }
        else if (status == Strophe.Status.AUTHFAIL)
        {
           jQuery('#connection_create').hideLoading();  
           log("AUTHFAIL from jabber server");
        }
        
        if (connected)
        {
           $("div#connection_create").addClass("hidden");
           $("div#connection_destroy").removeClass("hidden");
        }
        else
        {
           $("div#connection_create").removeClass("hidden");
           $("div#connection_destroy").addClass("hidden");            
        }
    }    
};

$(function()
{
    // Accordion
    $("#main_accordion").accordion({header: "h3"});

    // Tabs
    $('#main_tabs').tabs();
    
    $("div#connection_destroy").addClass("hidden");
   
    $("#xmpp_connect").click(Xmpp.connect);
    $("#xmpp_disconnect").click(Xmpp.disconnect);
});